package all.com.jinyongqunxiax.Utility;

import com.tickaroo.tikxml.XmlReader;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import okio.BufferedSource;
import okio.Okio;
import okio.Buffer;
import okio.BufferedSource;

public class TikXmlUtils {
    public static XmlReader readerFrom(String xml) {
        return XmlReader.of(new Buffer().writeUtf8(xml));
    }

    public static XmlReader readerFromFile(String filePath) throws IOException {
        return XmlReader.of(Okio.buffer(Okio.source(new File(getResourcePath(filePath)))));
    }

    public static BufferedSource sourceForFilePath(String filePath) throws IOException {
        File file = new File(filePath);
        return sourceForFile(file);
    }

    public static BufferedSource sourceForFile(File file) throws IOException {
        return Okio.buffer(Okio.source(file));
    }

    public static BufferedSource sourceFromString(String xml) {
        return new Buffer().writeUtf8(xml);
    }

    /**
     * Get the resource path
     */
    private static String getResourcePath(String resPath) {
        URL resource = TikXmlUtils.class.getClassLoader().getResource(resPath);
        return resource.getFile();
    }


    /**
     * Converts the buffers content to a String
     *
     * @param buffer
     * @return
     */
    public static String bufferToString(Buffer buffer) {
        return buffer.readUtf8();
    }

}
